/**
 * 图片状态检测工具
 * 检测AI生成图片的可访问性，提供友好的用户体验
 */

export interface ImageStatus {
  url: string
  status: 'loading' | 'success' | 'expired' | 'error'
  error?: string
  retryCount?: number
}

class ImageStatusChecker {
  private cache = new Map<string, ImageStatus>()
  private readonly MAX_RETRY = 2
  private readonly TIMEOUT = 5000 // 5秒超时

  /**
   * 检查图片状态
   */
  async checkImageStatus(url: string): Promise<ImageStatus> {
    // 检查缓存
    const cached = this.cache.get(url)
    if (cached && cached.status !== 'loading') {
      return cached
    }

    // 设置加载状态
    const status: ImageStatus = { url, status: 'loading', retryCount: 0 }
    this.cache.set(url, status)

    try {
      const isAccessible = await this.testImageAccess(url)
      
      if (isAccessible) {
        status.status = 'success'
      } else {
        status.status = 'expired'
        status.error = '图片链接已过期'
      }
    } catch (error) {
      status.status = 'error'
      status.error = error instanceof Error ? error.message : '图片加载失败'
    }

    this.cache.set(url, status)
    return status
  }

  /**
   * 批量检查图片状态
   */
  async batchCheckStatus(urls: string[]): Promise<Map<string, ImageStatus>> {
    const promises = urls.map(url => this.checkImageStatus(url))
    const results = await Promise.allSettled(promises)
    
    const statusMap = new Map<string, ImageStatus>()
    results.forEach((result, index) => {
      const url = urls[index]
      if (result.status === 'fulfilled') {
        statusMap.set(url, result.value)
      } else {
        statusMap.set(url, {
          url,
          status: 'error',
          error: '检查失败'
        })
      }
    })

    return statusMap
  }

  /**
   * 测试图片是否可访问
   */
  private async testImageAccess(url: string): Promise<boolean> {
    return new Promise((resolve) => {
      const img = new Image()
      const timeoutId = setTimeout(() => {
        resolve(false)
      }, this.TIMEOUT)

      img.onload = () => {
        clearTimeout(timeoutId)
        resolve(true)
      }

      img.onerror = () => {
        clearTimeout(timeoutId)
        resolve(false)
      }

      // 添加随机参数避免缓存
      const testUrl = url + (url.includes('?') ? '&' : '?') + '_t=' + Date.now()
      img.src = testUrl
    })
  }

  /**
   * 重试检查图片
   */
  async retryCheck(url: string): Promise<ImageStatus> {
    const cached = this.cache.get(url)
    const retryCount = (cached?.retryCount || 0) + 1

    if (retryCount > this.MAX_RETRY) {
      return {
        url,
        status: 'error',
        error: '重试次数已达上限',
        retryCount
      }
    }

    // 清除缓存，重新检查
    this.cache.delete(url)
    const status = await this.checkImageStatus(url)
    status.retryCount = retryCount
    
    return status
  }

  /**
   * 清除缓存
   */
  clearCache() {
    this.cache.clear()
  }

  /**
   * 获取缓存统计
   */
  getCacheStats() {
    const stats = {
      total: this.cache.size,
      success: 0,
      expired: 0,
      error: 0,
      loading: 0
    }

    for (const status of this.cache.values()) {
      stats[status.status]++
    }

    return stats
  }
}

export const imageStatusChecker = new ImageStatusChecker()

/**
 * 判断是否为AI生成图片的临时URL
 */
export function isTemporaryImageUrl(url: string): boolean {
  // 硅基流动等服务商的临时URL特征
  const temporaryPatterns = [
    /siliconflow/i,
    /temp/i,
    /temporary/i,
    /token=/i,
    /expires=/i,
    /signature=/i
  ]

  return temporaryPatterns.some(pattern => pattern.test(url))
}

/**
 * 生成图片占位符
 */
export function generateImagePlaceholder(width = 400, height = 300, text = '图片已过期'): string {
  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return ''

  // 绘制背景
  ctx.fillStyle = '#f5f5f5'
  ctx.fillRect(0, 0, width, height)

  // 绘制边框
  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 2
  ctx.strokeRect(1, 1, width - 2, height - 2)

  // 绘制图标 (简单的图片图标)
  ctx.fillStyle = '#999'
  ctx.font = '48px Arial'
  ctx.textAlign = 'center'
  ctx.fillText('🖼️', width / 2, height / 2 - 20)

  // 绘制文字
  ctx.font = '16px Arial'
  ctx.fillText(text, width / 2, height / 2 + 30)

  return canvas.toDataURL()
}

export default imageStatusChecker
